<script lang="ts" setup>
  import { reactive, ref, onMounted, watch, onUnmounted, onBeforeMount } from 'vue'
  import { ElMessageBox } from 'element-plus'
  const emit = defineEmits(['search'])
  const searchBody: any = ref(null)
  const searchList: any = ref(null)
  const chosedSearch: any = ref(null)
  let searchContent = ref('')
  let searchBodyWidth = ref(0)
  let searchListWidth = ref(0)
  let searchArr = reactive<Array<{ [key: string]: string }>>([])
  const searchFlag = reactive({ first: false, second: false })
  let radio = ref('')
  const second = reactive<{ [key: string]: any }>({
    key: '',
    secondList: {},
    opChose: false
  })
  const props = defineProps({
    search: {
      type: Object,
      default: {
        inputSearch: {}
      }
    },
    ys: Object,
    searchConArr: Array<{ [key: string]: string }>
  })

  const clearSearchArr = () => {
    searchArr.length = 0
    emit('search', searchArr)
  }
  // 删除已选搜索条件
  const deleteSearchItem = (item: any) => {
    let Arr = [...searchArr]
    let arr = Arr.filter((value) => {
      return item.key !== value.key
    })
    Arr.length = 0
    Arr.push(...arr)
    emit('search', Arr)
  }
  const dealKey = (value: any, ys: any) => {
    return ys[value]
  }
  const dealVal = (value: string, item: any) => {
    if (props.search) {
      return value.split(';').join(' | ')
    }
  }
  // 点击进行重新搜索
  const reChose = (param: any) => {
    if (props.search) {
      if (props.search.inputSearch[param.key]) {
        return
      }
      let temp = {
        data: [
          {
            choseFlag: false,
            dataList: [{ flag: false, value: '' }],
            flag: false,
            value: ''
          }
        ],
        num: null
      }
      for (let k in props.search) {
        if (props.search[k][param.key]) {
          temp = JSON.parse(JSON.stringify(props.search[k][param.key]))
        }
      }
      let valueArr = param.value.split(';')
      temp.data &&
        temp.data.forEach((item) => {
          if (temp.num) {
            item.choseFlag = false
            item.dataList.forEach((innerItem) => {
              innerItem.flag = valueArr.some((val: any) => {
                return val === innerItem.value
              })
            })
            item.flag = item.dataList.every((innerItem) => {
              return innerItem.flag
            })
          } else {
            item.flag = valueArr.some((val: any) => {
              return item.value === val
            })
          }
        })
      second.key = param.key
      second.secondList = temp
      searchFlag.first = false
      searchFlag.second = true
    }
  }
  const switchChoseList = () => {
    if (!searchFlag.first && !searchFlag.second && props.search) {
      // 判断searchContent是否有值
      if (Object.keys(props.search.choseSearch).length || searchContent.value.length) {
        searchFlag.first = true
      }
    }
  }
  // 删除input里面和searcharr的内容
  const deleteAll = (event: any) => {
    if (event.keyCode === 8 && !searchContent.value) {
      searchArr.splice(0, searchArr.length)
      searchFlag.first = false
      searchFlag.second = false
      emit('search', searchArr)
    }
  }
  // 按照key进行搜索
  const addInputSearch = (key: any, value: any) => {
    let arr = [...searchArr]
    if (searchContent.value) {
      let index1 = 0
      let flag = arr.every((item, index) => {
        if (item.key === key) {
          index1 = index
        }
        return item.key !== key
      })
      if (flag) {
        arr.push({ key: key, value: searchContent.value })
      } else {
        arr[index1].value = searchContent.value
      }
      searchContent.value = ''
      searchFlag.first = false
      emit('search', arr)
    } else {
      ElMessageBox.alert('请填写搜索内容', {
        confirmButtonText: '确定'
      })
    }
  }
  const addSecondList = (key: any, value: any) => {
    let flag = searchArr.every((item) => {
      return item.key !== key
    })
    let temp = JSON.parse(JSON.stringify(value))
    if (flag) {
      temp.data.forEach((item: { flag: boolean; choseFlag: boolean; dataList: any[] }) => {
        item.flag = false
        if (value.num) {
          item.choseFlag = false
          item.dataList.forEach((innerItem) => {
            innerItem.flag = false
          })
        }
      })
    } else {
      let chosed: { [key: string]: string } = {}
      searchArr.forEach((item) => {
        if (item.key === key) {
          chosed = item
        }
      })
      let valueArr = chosed.value.split(';')
      temp.data.forEach((item: { choseFlag: boolean; dataList: any[]; flag: boolean; value: string }) => {
        if (temp.num) {
          item.choseFlag = false
          item.dataList.forEach((innerItem) => {
            innerItem.flag = valueArr.some((val) => {
              return val === innerItem.value
            })
          })
          item.flag = item.dataList.every((innerItem) => {
            return innerItem.flag
          })
        } else {
          item.flag = valueArr.some((val) => {
            return item.value === val
          })
        }
      })
    }
    searchFlag.first = false
    searchFlag.second = true
    second.key = key
    second.secondList = temp
  }
  const toChosed = () => {
    let arr = [...searchArr]
    let key = second.key
    let index1 = 0
    let value = ''
    let flag1 = arr.every((item, index) => {
      if (item.key === key) {
        index1 = index
      }
      return item.key !== key
    })
    value = genKey(second.secondList)
    if (flag1) {
      arr.push({ key: key, value: value })
    } else {
      arr[index1].value = value
    }
    searchFlag.first = false
    searchFlag.second = false
    emit('search', arr)
  }
  const cancelAdd = () => {
    searchFlag.second = false
  }
  const genKey = (data: { data: any[]; num: any }) => {
    let choseArr: any[] = []
    data.data.forEach((item) => {
      if (data.num) {
        if (item.flag) {
          choseArr = choseArr.concat(item.dataList)
        } else {
          item.dataList.forEach((innerItem: { flag: any }) => {
            if (innerItem.flag) {
              choseArr.push(innerItem)
            }
          })
        }
      } else {
        if (item.flag) {
          choseArr.push(item)
        }
      }
    })
    let value = choseArr.reduce((init, item) => {
      return init ? init + ';' + item.value : item.value
    }, '')
    return value
  }
  const handler = () => {
    searchFlag.first = false
    searchFlag.second = false
  }
  watch(searchContent, (value) => {
    if (value.length) {
      searchFlag.first = true
    }
  })
  watch(
    () => searchFlag.first,
    (value) => {
      if (!value) {
        searchListWidth.value = searchList.offsetWidth * 1
        second.opChose = false
      }
      if (chosedSearch.offsetWidth) {
        let cs = chosedSearch.offsetWidth * 1
        let sl = searchListWidth.value * 1
        let sb = searchBodyWidth.value
        if (cs > sb - sl) {
          searchList.style.left = sb - sl + 'px'
        } else {
          searchList.style.left = cs + 'px'
        }
      }
    }
  )
  const setopChose2 = (item: { flag: boolean; dataList: any[] }, index: any) => {
    second.secondList.data.forEach((p: any, i: any) => {
      if (i != index) {
        p.flag = false
      }
    })
    if (item.dataList) {
      item.dataList.forEach((innerItem) => {
        innerItem.flag = !innerItem.flag
      })
    }
  }
  onMounted(() => {
    if (document.addEventListener) {
      document.addEventListener('click', handler, false)
    } else {
      document['onclick'] = handler
    }
    searchBodyWidth.value = searchBody.offsetWidth * 1
  })

  if (props.searchConArr) {
    searchArr = props.searchConArr
  }
  onUnmounted(() => {
    if (document.removeEventListener) {
      document.removeEventListener('click', handler, false)
    } else {
      document['onclick'] = null
    }
  })
</script>
<template>
  <div id="search" @click.stop>
    <div class="searchBody" ref="searchBody">
      <div class="deleteIcon" @click="clearSearchArr">
        <el-icon v-if="searchArr.length"><component is="Close" /></el-icon>
        <el-icon v-else><component is="Search" /></el-icon>
      </div>
      <div class="chosedSearch clearfix" ref="chosedSearch">
        <div class="chosedSearchItem clearfix" v-for="(item, index) in searchArr" :key="index">
          <div class="searchKey">
            <div class="searchInner">
              <span @click="deleteSearchItem(item)">{{ dealKey(item.key, ys) }}</span>
              :<span @click="reChose(item)" class="pd">{{ $t(`${dealVal(item.value, item)}`) }}</span>
              <el-icon @click="deleteSearchItem(item)"><component is="CircleCloseFilled" /></el-icon>
            </div>
          </div>
        </div>
      </div>
      <div class="searchInput">
        <input
          type="text"
          id="searchContent"
          autocomplete="off"
          :placeholder="'搜索或者匹配你需要的结果...'"
          @click="switchChoseList"
          @keydown="deleteAll"
          v-model="searchContent"
        />
      </div>
    </div>
    <div class="searchList" ref="searchList">
      <ul class="firstSearchClass" v-show="searchFlag.first">
        <li v-for="(value, key) in props.search.inputSearch" :key="key" @click="addInputSearch(key, value)">
          <a href="javascript:void(0)">
            {{ `按照${value.name}进行搜索` }}
            <i class="hae-icon icon-search"></i>
          </a>
        </li>
        <li v-for="(value, key) in search.choseSearch" :key="key" v-show="key" @click="addSecondList(key, value)">
          {{ value.name }}
        </li>
      </ul>
      <div class="secondSearchClassWrap" v-show="searchFlag.second">
        <ul class="secondSearchClass" ref="secondSearchClass">
          <li v-for="(item, index) in second.secondList.data" :key="index">
            <div class="one">
              <el-checkbox v-model="item.flag" :label="$t(item.text)" @change="setopChose2(item, index)" />
            </div>
          </li>
        </ul>
        <div class="secondClassButton">
          <button class="btn new" @click="toChosed">确定</button>
          <button class="btn" @click="cancelAdd">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  #search {
    position: relative;
    width: 100%;
    border: 1px solid $border-color;
    border-radius: 2px;
    font-size: 12px;
    color: $text-color;
    .deleteIcon {
      position: absolute;
      top: 50%;
      margin-top: -11px;
      right: 10px;
      font-weight: 600;
      font-size: 15px;
      color: $action-color;
      cursor: pointer;
    }
    .searchBody {
      width: 96%;
      height: 32px;
      display: -ms-flexbox;
      display: flex;
      font-size: 14px;
      overflow-x: auto;
      overflow-y: hidden;
      padding-right: 10px;
      &::-webkit-scrollbar {
        height: 5px;
        width: 100px;
      }
      &::-webkit-scrollbar-thumb {
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: rgba(0, 0, 0, 0.1);
        border-radius: 0;
      }
      .chosedSearch {
        height: 100%;
        display: flex;
        .chosedSearchItem {
          height: 100%;
          float: left;
          padding: 0 10px;
          white-space: nowrap;
          overflow: hidden;
          font-size: 12px;
          .searchKey {
            color: #666;
            display: inline-block;
            height: 100%;
            line-height: 31px;
            font-weight: 500;
            .searchInner {
              display: inline;
              background-color: $bac-color;
              padding: 3px;
            }
            i {
              cursor: pointer;
              color: #ccc;
            }
            span {
              cursor: pointer;
              font-size: 12px;
              border-radius: 2px;
            }
            .pd {
              padding: 0 10px 0 3px;
            }
          }
        }
      }
      .searchInput {
        height: 100%;
        width: 100%;
        min-width: 20%;
        position: relative;
        font-size: 14px;
        clear: both;
        #searchContent {
          display: inline-block;
          height: 100%;
          width: calc(100% - 5px);
          border: none;
          outline-style: none;
          font-size: 12px;
          padding-left: 5px;
        }
      }
    }
    .searchList {
      position: absolute;
      top: 32px;
      left: 0px;
      z-index: 10;
      .secondSearchClassWrap,
      .firstSearchClass {
        min-width: 200px;
        background-color: #fff;
        border: 1px solid $border-color;
        border-radius: 3px;
        .secondClassButton {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 40px;
          border-top: 1px solid $border-color;
          .btn {
            height: 20px;
            width: 40px;
          }
          .btn:first-child {
            margin-right: 10px;
          }
        }
      }
      .secondSearchClassWrap {
        max-height: 300px;
        overflow-y: auto;

        .secondHead {
          padding: 5px 10px;
          border-bottom: 1px solid $border-color;
          height: 30px;
          line-height: 20px;
          font-weight: 500;
          &:hover {
            background: #e6f3ff;
            cursor: pointer;
          }
        }
        .aui-svg {
          margin-right: 5px;
        }
      }
      .firstSearchClass,
      .secondSearchClass {
        padding: 0;
        list-style: none;
        li {
          input {
            display: inline-block;
            margin-top: 3px;
          }
          .one,
          .two {
            padding: 0 10px;
            height: 30px;
            line-height: 30px;
          }
          .two {
            margin-left: 16px;
          }
          &:hover {
            background: #e6f3ff;
            cursor: pointer;
          }
        }
      }
      .firstSearchClass {
        li {
          padding: 0 10px;
          height: 30px;
          line-height: 30px;
          color: $text-color;
        }
        li:hover {
          color: $main-color;
        }
        a {
          color: $text-color;
          text-decoration-line: none;
        }
        a:hover {
          color: $main-color;
        }
      }
      .name-width {
        display: inline-block;
        max-width: 240px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        vertical-align: bottom;
      }
    }
  }
</style>
